<template>
<div>
    <h2 style="text-align: center;">用户借款页面</h2>
    <table class="table table-bordered" border="1">
        <tr>
            <td>借款款项名称</td>
            <td>{{ info.B_Name }}</td>
        </tr>

        <tr>
            <td>最高金额</td>
            <td>{{ info.B_MaxMoney }}</td>
        </tr>

        <tr>
            <td>利息</td>
            <td>{{ info.BI_Interest }}</td>
        </tr>

        <tr>
            <td>借款金额</td>
            <td>
                <input type="text" placeholder="请输入借款金额" v-model="Bmoney" @change="GetUserBorrowMoney">
            </td>
        </tr>

        <tr>
            <td>每月还款金额</td>
            <td>{{ Monthmoney.toFixed(2) }}CNY</td>
        </tr>

        <tr>
            <td colspan="2" style="text-align: center;">
                <input type="button" value="确认借款" @click="SaveData">
            </td>
        </tr>
    </table>
</div>
</template>

<script setup lang="ts">
import {useRoute,useRouter} from 'vue-router'
import {ref,onMounted} from 'vue'
import axios from 'axios';
import { useUserStore } from '../../store/index.ts';

//创建仓库实例
const useStore=useUserStore();

//创建路由实例
const route=useRoute();
//创建路由操作对象
const router=useRouter();

//创建响应式数据
const info=ref({
    B_Name:"",
    B_MaxMoney:0,
    BI_Interest:0,
    BI_Year:0
})

const Bmoney=ref("");
const Monthmoney=ref(0)

//创建生命周期函数钩
onMounted(()=>{
    LoadData()
})

//完成加载数据
const LoadData=()=>{
    axios.get("https://localhost:44321/api/Borrows/GetBorrowMoney",
        {
            params:{
                Bid:route.params.Bid
            }
        }
    )
    .then(res=>{
        console.log(res.data)
        info.value=res.data[0]
    })
}

//获取用户还款金额
const GetUserBorrowMoney=()=>{
    //每月还款金额=(本金+利息)/年份/12
    Monthmoney.value=(Number(Bmoney.value)+(Number(Bmoney.value)*info.value.BI_Interest/100))/info.value.BI_Year/12;
}

//保存用户借款信息
const SaveData=()=>{
    axios.post("https://localhost:44321/api/Borrows/AddUserBorrowMoneyInfo",
        {
            U_Id:useStore.Uid,
            B_Id:route.params.Bid,
            UB_Money:Bmoney.value
        }
    )
    .then(res=>{
        if(res.data>0)
        {
            alert('用户借款成功');
            router.push("/ShowUserBorrowMoney")
        }
        else
        {
            alert('用户借款失败!!!');
        }
    })
}

</script>